#include "qremovedatadialog.h"
#include "ui_qremovedatadialog.h"

#include "../../libs/sharedLib/qprojectcore.h"
#include "../../libs/sharedLib/qmemerymanager.h"

QRemoveDataDialog::QRemoveDataDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::QRemoveDataDialog)
{
    ui->setupUi(this);

    initTree();
}

QRemoveDataDialog::~QRemoveDataDialog()
{
    delete ui;
}

void QRemoveDataDialog::initTree()
{
    SHAREDLIB::QMemeryManager *m=SHAREDLIB::QProjectCore::getCore()->memeryManager();

    int count=m->dataCount();
    QObject *obj;
    QTreeWidgetItem* item;
    QTreeWidgetItem* parent;
    QString group;
    QString name;
    for(int i=0;i<count;i++)
    {
        obj=m->getData(i);
        group=obj->property("group").toString();
        name=obj->property("name").toString();
        parent=m_groups.value(group);
        if(parent==NULL)
        {
            parent=new QTreeWidgetItem(ui->dataList);
            parent->setText(0,group);
            m_groups.insert(group,parent);
            parent->setExpanded(true);
        }
        item=new QTreeWidgetItem(parent);
        item->setText(0,name);
        item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable);
        item->setCheckState(0,Qt::Unchecked);
        m_items.append(item);
    }

}

void QRemoveDataDialog::on_okBtn_clicked()
{
    SHAREDLIB::QMemeryManager *m=SHAREDLIB::QProjectCore::getCore()->memeryManager();
    QList<QObject*> list;
    QObject *obj;
    foreach(QTreeWidgetItem *item,m_items)
    {
        if(item->checkState(0)==Qt::Checked)
        {
            obj=m->getData(item->parent()->text(0),item->text(0));
            if(obj!=NULL)
            {
                list.append(obj);
            }
        }
    }

    if(list.size()>1)
    {
        m->removeDatas(list);
    }
    else if(list.size()==1)
    {
        m->removeData(list.first()->property("group").toString(),list.first()->property("name").toString());
    }

    close();
}

void QRemoveDataDialog::on_cancelBtn_clicked()
{
    close();
}
